import { createPersistStore, BaseState } from './index'
import { Character, CreateCharacterParams } from '@/types/character'
import { nanoid } from 'nanoid'

interface CharacterState extends BaseState {
  characters: Character[];
  currentCharacter: Character | null;
  
  // 操作函数
  fetchCharacters: (projectId: string) => Promise<Character[]>;
  getCharactersByProject: (projectId: string) => Character[];
  createCharacter: (params: CreateCharacterParams) => Promise<Character>;
  updateCharacter: (id: string, updates: Partial<Character>) => Promise<void>;
  deleteCharacter: (id: string) => Promise<void>;
  selectCharacter: (id: string) => void;
}

// 初始状态
const initialState = {
  characters: [],
  currentCharacter: null,
  isLoading: false,
  error: null
}

export const useCharacterStore = createPersistStore<CharacterState>(
  'characters',
  initialState as any,
  (set, get) => ({
    ...initialState,
    
    fetchCharacters: async (projectId) => {
      set({ isLoading: true, error: null });
      
      try {
        // 在实际实现中，这里会从API或本地存储获取数据
        // 现在我们使用存储在Zustand中的数据
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        const characters = get().characters.filter(c => c.projectId === projectId);
        set({ isLoading: false });
        return characters;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    getCharactersByProject: (projectId) => {
      return get().characters.filter(c => c.projectId === projectId)
        .sort((a, b) => a.name.localeCompare(b.name));
    },
    
    createCharacter: async (params) => {
      set({ isLoading: true, error: null });
      
      try {
        // 创建新角色
        const now = new Date().toISOString();
        const newCharacter: Character = {
          id: nanoid(),
          projectId: params.projectId,
          name: params.name,
          description: params.description || '',
          traits: params.traits || [],
          relationships: params.relationships || [],
          background: params.background || '',
          gallery: params.gallery || [],
          notes: params.notes || '',
          createdAt: now,
          updatedAt: now
        };
        
        // 更新状态
        set(state => ({ 
          characters: [...state.characters, newCharacter],
          currentCharacter: newCharacter,
          isLoading: false 
        }));
        
        return newCharacter;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    updateCharacter: async (id, updates) => {
      set({ isLoading: true, error: null });
      
      try {
        // 更新角色
        set(state => {
          const characters = state.characters.map(c => 
            c.id === id 
              ? { ...c, ...updates, updatedAt: new Date().toISOString() } 
              : c
          );
          
          // 如果当前选中的角色被更新，也更新currentCharacter
          const currentCharacter = state.currentCharacter?.id === id
            ? { ...state.currentCharacter, ...updates, updatedAt: new Date().toISOString() }
            : state.currentCharacter;
            
          return { characters, currentCharacter, isLoading: false };
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    deleteCharacter: async (id) => {
      set({ isLoading: true, error: null });
      
      try {
        // 删除角色
        set(state => {
          const characters = state.characters.filter(c => c.id !== id);
          
          // 如果删除的是当前选中的角色，重置currentCharacter
          const currentCharacter = state.currentCharacter?.id === id
            ? null
            : state.currentCharacter;
            
          return { characters, currentCharacter, isLoading: false };
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    selectCharacter: (id) => {
      const { characters } = get();
      const character = characters.find(c => c.id === id) || null;
      set({ currentCharacter: character });
    }
  })
); 